const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

let homeDir =  path.dirname(app.getPath('exe'))
let electronPath = path.join(homeDir, 'electron.exe')
console.log(electronPath)

require('electron-reload')(path.join(__dirname), {
  electron: electronPath // Windows
  // 对于 macOS，使用 'Electron.app/Contents/MacOS/Electron'
});

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: true
    }
  });

  win.loadFile(path.join(__dirname, 'index.html'));

  // 设置 CSP
  win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': ['default-src \'self\'; script-src \'self\'; connect-src \'self\' https://api.example.com']
      }
    })
  });  
}

function createComposeWindow() {
  const composeWin = new BrowserWindow({
    width: 600,
    height: 400,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  composeWin.loadFile(path.join(__dirname, 'compose.html'));

  composeWin.webContents.on('did-finish-load', () => {
    if (replyToEmail) {
      composeWin.webContents.send('reply-to-email', replyToEmail);
    }
  });
}

function createSettingsWindow() {
  const settingsWin = new BrowserWindow({
    width: 400,
    height: 300,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: true
    }
  });

  settingsWin.loadFile(path.join(__dirname, 'settings.html'));
  // 设置 CSP
  settingsWin.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': ['default-src \'self\'; script-src \'self\'; connect-src \'self\' https://api.example.com']
      }
    })
  });  
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

ipcMain.on('open-compose-window', (event, replyToEmail) => {
  createComposeWindow(replyToEmail);
});

// 在适当的位置添加以下代码
ipcMain.on('open-settings-window', () => {
  createSettingsWindow();
});

ipcMain.on('settings-updated', () => {
  // 通知主窗口设置已更新
  mainWindow.webContents.send('reload-email-service');
});
